import React, { useState, useEffect } from 'react';
import { Play, Pause, Square, Settings, FileText, AlertCircle, CheckCircle, Upload } from 'lucide-react';
import { PluginState, DeliveryStats, PluginSettings } from '@/types';
import { getState, saveState, getSettings, getTodayDeliveryCount, getDeliveryRecords } from '@/utils/storage';

const PopupApp: React.FC = () => {
  const [state, setState] = useState<PluginState>({
    isRunning: false,
    isPaused: false,
    todayDeliveryCount: 0,
    totalDeliveryCount: 0,
    currentPage: 1
  });
  
  const [stats, setStats] = useState<DeliveryStats>({
    todayCount: 0,
    totalCount: 0,
    successRate: 0,
    recentRecords: []
  });
  
  const [settings, setSettings] = useState<PluginSettings | null>(null);
  const [showResumeWarning, setShowResumeWarning] = useState(false);

  // 初始化数据
  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      const [currentState, currentSettings, todayCount, records] = await Promise.all([
        getState(),
        getSettings(),
        getTodayDeliveryCount(),
        getDeliveryRecords()
      ]);

      setState(currentState);
      setSettings(currentSettings);
      
      const successCount = records.filter(r => r.status === 'success').length;
      const successRate = records.length > 0 ? (successCount / records.length) * 100 : 0;
      
      setStats({
        todayCount: todayCount,
        totalCount: records.length,
        successRate: Math.round(successRate),
        recentRecords: records.slice(0, 5)
      });
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  };

  // 开始投递
  const handleStart = async () => {
    if (!settings) return;
    
    // 检查今日投递限制
    if (stats.todayCount >= settings.dailyLimit) {
      alert(`今日投递已达上限 ${settings.dailyLimit} 条`);
      return;
    }

    // 检查是否在Boss直聘页面
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab.url?.includes('zhipin.com')) {
      alert('请先打开Boss直聘网站，搜索并筛选要投递的职位');
      return;
    }

    // 显示简历提醒
    setShowResumeWarning(true);
    setTimeout(() => setShowResumeWarning(false), 3000);

    const newState = { ...state, isRunning: true, isPaused: false };
    setState(newState);
    await saveState(newState);

    // 发送消息给content script开始投递
    chrome.tabs.sendMessage(tab.id!, { action: 'START_DELIVERY', settings });
  };

  // 暂停投递
  const handlePause = async () => {
    const newState = { ...state, isPaused: !state.isPaused };
    setState(newState);
    await saveState(newState);

    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.tabs.sendMessage(tab.id!, { 
      action: state.isPaused ? 'RESUME_DELIVERY' : 'PAUSE_DELIVERY' 
    });
  };

  // 停止投递
  const handleStop = async () => {
    const newState = { ...state, isRunning: false, isPaused: false };
    setState(newState);
    await saveState(newState);

    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.tabs.sendMessage(tab.id!, { action: 'STOP_DELIVERY' });
  };

  // 打开设置页面
  const openSettings = () => {
    if (chrome.runtime.openOptionsPage) {
      chrome.runtime.openOptionsPage();
    } else {
      // 备用方案：在新标签页中打开设置页面
      chrome.tabs.create({
        url: chrome.runtime.getURL('options.html')
      });
    }
  };

  // 获取状态指示器
  const getStatusIndicator = () => {
    if (state.isRunning && !state.isPaused) {
      return <span className="status-indicator status-running"></span>;
    } else if (state.isPaused) {
      return <span className="status-indicator status-paused"></span>;
    } else {
      return <span className="status-indicator status-stopped"></span>;
    }
  };

  // 获取状态文本
  const getStatusText = () => {
    if (state.isRunning && !state.isPaused) return '运行中';
    if (state.isPaused) return '已暂停';
    return '已停止';
  };

  return (
    <div className="w-full h-full bg-gray-50">
      {/* 顶部状态栏 */}
      <div className="gradient-bg text-white p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <FileText className="w-6 h-6 mr-2" />
            <h1 className="text-lg font-semibold">Boss投递助手</h1>
          </div>
          <div className="flex items-center text-sm">
            {getStatusIndicator()}
            {getStatusText()}
          </div>
        </div>
      </div>

      {/* 简历提醒 */}
      {showResumeWarning && (
        <div className="warning-card p-4 m-4 animate-pulse">
          <div className="flex items-center">
            <div className="bg-amber-100 p-2 rounded-full mr-3">
              <Upload className="w-5 h-5 text-amber-600" />
            </div>
            <div>
              <p className="text-sm font-semibold text-amber-800">温馨提示</p>
              <p className="text-xs text-amber-700">
                请确保已在Boss直聘上传完整简历后再开始投递
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="p-5 space-y-6">
        {/* 功能控制区域 */}
        <div className="flex space-x-3">
          {!state.isRunning ? (
            <button onClick={handleStart} className="btn-primary flex-1 flex items-center justify-center">
              <Play className="w-5 h-5 mr-2" />
              开始投递
            </button>
          ) : (
            <>
              <button onClick={handlePause} className="btn-secondary flex-1 flex items-center justify-center">
                {state.isPaused ? <Play className="w-5 h-5 mr-2" /> : <Pause className="w-5 h-5 mr-2" />}
                {state.isPaused ? '继续' : '暂停'}
              </button>
              <button onClick={handleStop} className="btn-secondary flex-1 flex items-center justify-center">
                <Square className="w-5 h-5 mr-2" />
                停止
              </button>
            </>
          )}
          <button onClick={openSettings} className="btn-icon">
            <Settings className="w-5 h-5" />
          </button>
        </div>

        {/* 统计数据卡片 */}
        <div className="grid grid-cols-3 gap-4">
          <div className="stat-card text-center hover-lift">
            <div className="stat-number">{stats.todayCount}</div>
            <div className="text-xs text-gray-600 font-medium mt-1">今日投递</div>
          </div>
          <div className="stat-card text-center hover-lift">
            <div className="stat-number">{stats.totalCount}</div>
            <div className="text-xs text-gray-600 font-medium mt-1">总投递数</div>
          </div>
          <div className="stat-card text-center hover-lift">
            <div className="stat-number">{stats.successRate}%</div>
            <div className="text-xs text-gray-600 font-medium mt-1">成功率</div>
          </div>
        </div>

        {/* 投递限制提示 */}
        {settings && (
          <div className="info-card p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <div className="bg-blue-100 p-2 rounded-full mr-3">
                  <AlertCircle className="w-4 h-4 text-blue-600" />
                </div>
                <div>
                  <p className="text-sm font-semibold text-blue-800">今日进度</p>
                  <p className="text-xs text-blue-700">
                    {stats.todayCount}/{settings.dailyLimit} 条
                  </p>
                </div>
              </div>
              <div className="w-16 h-2 bg-blue-200 rounded-full overflow-hidden">
                <div 
                  className="h-full bg-gradient-to-r from-blue-400 to-blue-600 transition-all duration-500"
                  style={{ width: `${Math.min(100, (stats.todayCount / settings.dailyLimit) * 100)}%` }}
                ></div>
              </div>
            </div>
          </div>
        )}

        {/* 最近投递记录 */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-semibold text-gray-700">最近投递</h3>
            <span className="text-xs text-gray-500">{stats.recentRecords.length} 条记录</span>
          </div>
          <div className="space-y-3 max-h-40 overflow-y-auto custom-scrollbar">
            {stats.recentRecords.length > 0 ? (
              stats.recentRecords.map((record, index) => (
                <div key={index} className="record-item hover-lift">
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-semibold text-gray-900 truncate">
                      {record.jobTitle}
                    </div>
                    <div className="text-xs text-gray-500 truncate mt-1">
                      {record.companyName} · {record.location}
                    </div>
                  </div>
                  <div className="flex items-center ml-3">
                    {record.status === 'success' ? (
                      <div className="bg-green-100 p-1 rounded-full">
                        <CheckCircle className="w-4 h-4 text-green-600" />
                      </div>
                    ) : (
                      <div className="bg-red-100 p-1 rounded-full">
                        <AlertCircle className="w-4 h-4 text-red-600" />
                      </div>
                    )}
                  </div>
                </div>
              ))
            ) : (
              <div className="text-center py-8">
                <div className="bg-gray-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-3">
                  <FileText className="w-8 h-8 text-gray-400" />
                </div>
                <p className="text-gray-500 text-sm">暂无投递记录</p>
                <p className="text-gray-400 text-xs mt-1">开始投递后这里会显示记录</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default PopupApp;